import { ElMessage } from 'element-plus';
import { ref, reactive, nextTick } from 'vue';

const useTable = (queryInfo, requestTAB, config = { resType: 1 }) => {
  // 列表数据
  const listData = ref([]);

  const allData = ref({});

  // 列表数据总条数
  const total = ref(0);

  // 请求表格数据
  const requestTab = async () => {
    try {
      const res = await requestTAB(queryInfo);

      allData.value = res.data;

      if (res.code !== 200) {
        total.value = 0;

        listData.value = [];

        return ElMessage({
          message: '获取列表数据失败',
          type: 'error',
        });
      }

      if (config.resType == 1) {
        total.value = res.data.total;

        listData.value = res.data.data;
      }

      if (config.resType == 2) {
        let resData = res.data.list;

        total.value = resData.total;

        listData.value = resData.data;
      }

      if (config.resType == 3) {
        let resData = res.data.data;

        total.value = resData.total;

        listData.value = resData.data;
      }

      if (config.resType == 4) {
        let resData = res.data;

        listData.value = resData;
      }
    } catch (error) {
      console.log('queryList', orror);
    }
  };

  // 初始化表格
  const initTable = () => {
    requestTab();
  };

  // 分页页码该变
  const changePage = (currentPage, pageSize) => {
    console.log(77777, currentPage, pageSize);

    queryInfo.page = currentPage;
    queryInfo.limit = pageSize;
    requestTab();
  };

  // 查询表格
  const searchTable = () => {
    queryInfo.page = 1;

    nextTick(() => {
      requestTab();
    });
  };

  // 表格操作事件
  const operateTable = async ({ record, operateAPI }) => {
    const res = await operateAPI(record);
    if (res.code !== 200) return;
    searchTable();
  };

  return {
    total,
    listData,
    allData,
    initTable,
    changePage,
    searchTable,
    operateTable,
  };
};

export default useTable;
